﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Runtime.Serialization;

namespace NewsMine.Utilities
{
    public static class FileExetensions
    {
        public static void SerializeObjectToFile(string targetFile, object objectToStore)
        {
            Stream stream = File.Open(targetFile, FileMode.Create);
            BinaryFormatter bformatter = new BinaryFormatter();

            bformatter.Serialize(stream, objectToStore);
            stream.Close();
        }


        public static object DeserializeFromFile(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return null;
            }

            object mp = null;

            BinaryFormatter bformatter = new BinaryFormatter();

            //Open the file written above and read values from it.
            Stream stream = File.Open(fileName, FileMode.Open);

            bformatter = new BinaryFormatter();

            mp = bformatter.Deserialize(stream);
            stream.Close();

            return mp;
        }


        public static void SerializeObjectToFileUsingProtoBuff(string targetFile, object objectToStore)
        {
            FileStream fs = File.Open(targetFile, FileMode.Create);

            try
            {
                ProtoBuf.Serializer.Serialize(fs, objectToStore);
            }
            catch (SerializationException e)
            {
                throw new ApplicationException("Error while protobuff serializing the object to bytes, make sure you mark the object class as serializable", e);
            }
            finally
            {
                fs.Close();
            }
        }

        public static object DeserializeFromFile<T>(string fileName)
        {
            Stream stream = File.Open(fileName, FileMode.Open);

            try
            {
                object obj = ProtoBuf.Serializer.Deserialize<T>(stream);

                return obj;
            }
            catch
            {
                return null;
            }
            finally
            {
                stream.Close();
            }
        }

    }

    
}
